﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Linq;
using NHibernate;

namespace DD.NHibernateProvider
{
    public class GenericNHibernateContext : NHibernateContext
    {
        private ISession session;

        private string rootNamespace;

        public GenericNHibernateContext()
        {
            this.rootNamespace = "DD.Mappings";
            this.session = NHibernateFactory.Current.OpenSession();
        }

        protected override ISession ProvideSession()
        {
            return session;
        }

        public object GetTable(string entityName)
        {
            string fullEntityName = String.Concat(rootNamespace, ".", entityName);
            
            //var clazz = NHibernateFactory.Current.Configuration.GetClassMapping(fullEntityName).MappedClass;
            var clazz = NHibernateFactory.Current.Configuration.ClassMappings.Single(cm=>cm.IdentityTable.Name.Equals(entityName)).MappedClass;
            
            var mi = typeof(NHibernateExtensions).GetMethod("Linq", new Type[] { typeof(ISession) }).MakeGenericMethod(clazz);
            return mi.Invoke(null, new object[] { session });
        }
    }
}
